package com.shanks.home.module.component;

import java.util.ArrayList;

import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.shanks.home.R;

/**
 * ContentProvider
 * @author Shanks
 * @time 2014.05.28
 */
public class ComponentActivity extends Activity {
	
	private Button nameBtn, realizeBtn;
	private TextView contentTv;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.component_activity);
		initView();
		observerFun();
	}
	
	private void initView() {
		nameBtn = (Button)this.findViewById(R.id.component_content_provider_contact_name_btn);
		realizeBtn = (Button)this.findViewById(R.id.component_content_provider_realize_btn);
		contentTv = (TextView)this.findViewById(R.id.component_content_tv);
		
		nameBtn.setOnClickListener(onClickListener);
		realizeBtn.setOnClickListener(onClickListener);
	}
	
	private OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if (v == nameBtn) {
				getContactName();
			} else if (v == realizeBtn) {
				realizeFunc();
			}
		}
	};
	
	/**
	 * 使用系统的ContentProvider
	 */
	private void getContactName() {
		ArrayList<String> name = new ArrayList<String>();
		// 使用ContentResolver查找联系人数据
		Cursor cursor =  this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		// 遍历查询结果，获取系统中所有联系人
		while (cursor.moveToNext()) {
			// 获取联系人ID
//			String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
			// 获取联系人的名字
			String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			name.add(contactName);
		}
		
		String content = "";
		for (int i = 0; i < name.size(); i ++) {
			content += name.get(i);
		}
		contentTv.setText(content);
	}
	
	/**
	 * 实现ContentProvider
	 */
	private void realizeFunc() {
		// FIXME 暂未处理 
	}
	
	/**
	 * 监听ContentProvider
	 */
	private void observerFun() {
		this.getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new MyObserver(new Handler()));
	}
	
	private class MyObserver extends ContentObserver {

		public MyObserver(Handler handler) {
			super(handler);
		}
		
		@Override
		public void onChange(boolean selfChange) {
//			super.onChange(selfChange);
			getContactName();
		}
	}
}